package com.yjhh.chdataservice;

import com.yjhh.chdataservice.component.ESClientManager;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

//import com.yjhh.chdataservice.component.HDFSManager;

/**
 * Created by hlantian on 2017/10/12.
 */
@Component
@Log4j2
public class InitDataFactory implements CommandLineRunner {
    
    @Autowired
    private ESClientManager esClientManager;
    
    //@Autowired
    //private HDFSManager hdfsManager;
    
    private Map<String, JSONObject> deptInfoMap = null;
    
    private Map<String, Map<String, Object>> sysDicMap = null;
    
    
    @Override
    public void run(String... strings) throws Exception {
       log.info(">>>>>>>>>>>>>>>服务启动执行，执行加载数据等操作<<<<<<<<<<<<<");
        deptInfoMap = new HashMap<>();
        sysDicMap = new HashMap<>();
        
        initSysDicData();
        
        //hdfsManager.initFileSystem();
        
        initDeptInfoData();
        
       log.info(">>>>>>>>>>>>>>>服务启动执行，执行加载数据等操作结束<<<<<<<<<<<<<");
    }
    
    private void initSysDicData() {
        TransportClient esClient = esClientManager.getESClient();
        SearchRequestBuilder searchRequestBuilder = esClient.prepareSearch("sy_dict_inf")
                .setTypes("dict_inf").setSize(10000);
       log.info("reqeust dict_inf:" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> source = searchHit.getSource();
            sysDicMap.put(searchHit.getId(), source);
        }
    }
    
    
    private void initDeptInfoData() {
        int deptInfoCount = getDeptInfoCount();
        
        int pageUtil = 10000;
        //10000条数据为一个分页单位获取数据
        int pages = (deptInfoCount / pageUtil) + ((deptInfoCount % pageUtil) == 0 ? 0 : 1);
        for (int i = 0; i < pages; i++) {
            TransportClient esClient = esClientManager.getESClient();
            SearchRequestBuilder searchRequestBuilder = esClient.prepareSearch("sy_dept_info")
                    .setTypes("sy_dept")
                    .setFrom(i * pageUtil)
                    .setSize(pageUtil)
                    .addSort("deptid.keyword", SortOrder.ASC);
            
           log.info("reqeust sy_dept_info: " + (i + 1) + " page  " + searchRequestBuilder.toString());
            SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
            String resultJson = searchResponse.toString();
            parseDeptInfoToMap(resultJson);
        }
    }
    
    private int getDeptInfoCount() {
        TransportClient esClient = esClientManager.getESClient();
        SearchRequestBuilder searchRequestBuilder = esClient.prepareSearch("sy_dept_info")
                .setTypes("sy_dept")
                .setSize(0);
        
       log.info("reqeust sy_dept_info count: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        String jsonStr = searchResponse.toString();
       log.info("response sy_dept_info count:" + jsonStr);
        
        JSONObject rootJsonObject = JSONObject.fromObject(jsonStr);
        JSONObject hits = rootJsonObject.getJSONObject("hits");
        return hits.getInt("total");
    }
    
    private void parseDeptInfoToMap(String jsonStr) {
        JSONObject rootJsonObject = JSONObject.fromObject(jsonStr);
        JSONObject hits = rootJsonObject.getJSONObject("hits");
        JSONArray sysDeptDataArray = hits.getJSONArray("hits");
        for (int i = 0; i < sysDeptDataArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) sysDeptDataArray.get(i);
            String deptId = jsonObject.getString("_id");
            JSONObject sourceObject = jsonObject.getJSONObject("_source");
            deptInfoMap.put(deptId, sourceObject);
        }
    }
    
    public Map<String, JSONObject> getDeptInfoMap() {
        return deptInfoMap;
    }
    
    public Map<String, Map<String, Object>> getSysDicMap() {
        return sysDicMap;
    }
}
